package com.yejiali.backend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yejiali.backend.common.apicode.ResponseCodeEnum;
import com.yejiali.backend.common.constant.SystemConstant;
import com.yejiali.backend.entity.Comments;
import com.yejiali.backend.entity.Mentions;
import com.yejiali.backend.entity.Users;
import com.yejiali.backend.entity.Videos;
import com.yejiali.backend.entity.dto.CommentDTO;
import com.yejiali.backend.entity.vo.MentionsVO;
import com.yejiali.backend.mapper.CommentsMapper;
import com.yejiali.backend.mapper.MentionsMapper;
import com.yejiali.backend.mapper.UsersMapper;
import com.yejiali.backend.mapper.VideosMapper;
import com.yejiali.backend.response.Response;
import com.yejiali.backend.service.MentionsService;
import com.yejiali.backend.util.MessageUtil;
import com.yejiali.backend.util.RedisUtil;
import com.yejiali.backend.ws.WebSocketServer;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yejiali
 * @提醒表(Mentions)表服务实现类
 * @since 2025-08-15 14:19:32
 */
@Service
@Transactional
public class MentionsServiceImpl extends ServiceImpl<MentionsMapper, Mentions> implements MentionsService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private VideosMapper videosMapper;

    @Autowired
    private CommentsMapper commentMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Response<List<MentionsVO>> getMyMessage(Long userId) {
        //查询用户账号是否存在，状态是否正常
        Users users = usersMapper.selectById(userId);
        if (users == null || users.getAccountStatus() != 0) {
            return Response.error(400, "用户不存在或已被删除");
        }
        //查询用户的提醒信息
        QueryWrapper<Mentions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mentioned_user", userId);
        queryWrapper.orderByDesc("publish_time");
        List<Mentions> mentionsList = list(queryWrapper);
        //封装对象
        List<MentionsVO> mentionsVOS = BeanUtil.copyToList(mentionsList, MentionsVO.class);
        Set<Long> userIds = new HashSet<>();
        Set<Long> commentIds = new HashSet<>();
        //提取用户id和评论id
        mentionsVOS.forEach(mentionsVO -> {
            userIds.add(mentionsVO.getSenderId());
            commentIds.add(mentionsVO.getRefCommentId());
        });
        //批量查询
        Map<Long,Users> userMap=new HashMap<>();
        Map<Long,String> commentMap=new HashMap<>();
        //查询用户信息
        for(Users user1:usersMapper.selectBatchIds(userIds)){
            userMap.put(user1.getUserId(),user1);
        }
        //查询评论信息
        for(Comments comment1:commentMapper.selectBatchIds(commentIds)){
            commentMap.put(comment1.getCommentId(),comment1.getContent());
        }
        //填充用户信息和评论信息
        mentionsVOS.forEach(mentionsVO -> {
            mentionsVO.setSenderNickname(userMap.get(mentionsVO.getSenderId()).getNickname());
            mentionsVO.setSenderAvatar(userMap.get(mentionsVO.getSenderId()).getAvatar());
            mentionsVO.setContent(commentMap.get(mentionsVO.getRefCommentId()));
        });
        return Response.success(mentionsVOS,"@消息查询成功");
    }

    /**
     * 回复@我的评论
     * @param  commentDTO
     * @return
     */
    @Override
    public Response<String> replyComment(CommentDTO commentDTO)  {
        //判断视频id是否有效
        Videos videos = videosMapper.selectById(commentDTO.getVideoId());
        if (videos == null) {
            return Response.error(ResponseCodeEnum.NOT_FOUND.getCode(),"视频不存在");
        }
        //判断发布者id是否有效
        Users sender = usersMapper.selectById(commentDTO.getPublisherId());
        Users accepter = usersMapper.selectById(commentDTO.getAccepterId());
        if (sender == null || accepter==null) {
            return Response.error(ResponseCodeEnum.NOT_FOUND.getCode(),"评论用户不存在");
        }
        //封装数据
        Comments comment = BeanUtil.copyProperties(commentDTO, Comments.class);
        commentMapper.insert(comment);
        //发通知
        try {
            String message = MessageUtil.getMessage(SystemConstant.SEND_REPLY_MESSAGE, commentDTO.getAccepterId().toString(), "你被回复啦");
            ConcurrentHashMap<String, WebSocketServer> webSocketMap = WebSocketServer.getWebSocketMap();
            WebSocketServer webSocketServer = webSocketMap.get(commentDTO.getAccepterId().toString());
            if (webSocketServer != null) {
                webSocketServer.getSession().getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisUtil.hincr("user:unread:"+comment.getAccepterId(),"replyMessage",1);
        return Response.success("评论写入成功");
    }

    /**
     * 删除@我通知
     * @param mentionId
     * @return
     */
    @Override
    public Response<String> deleteMessage(Long mentionId) {
        //查询是否存在该通知
        Mentions mentions = getById(mentionId);
        if (mentions == null||mentions.getIsDeleted() == 1) {
            return Response.error(ResponseCodeEnum.NOT_FOUND.getCode(),"通知不存在或已被删除");
        }
        //删除改通知
        this.removeById(mentionId);
        return Response.success("删除成功");
    }

    /**
     * 新增我的@消息
     */
    @Override
    public Response<String> addAtMessage(CommentDTO commentDTO) throws JsonProcessingException {
        //拿到被@的用户id
        List<Long> atUserIds = commentDTO.getAtUserIds();
        //插入评论记录
        Comments comments = BeanUtil.copyProperties(commentDTO, Comments.class);
        commentMapper.insert(comments);
        //拿到评论id
        Long commentId = comments.getCommentId();
        List<Mentions> mentionsList=new ArrayList<>();
        //插入@表
        for (Long atUserId : atUserIds) {
            Mentions mentions = new Mentions();
            mentions.setRefCommentId(commentId);
            mentions.setMentionedUser(atUserId);
            mentions.setSenderId(commentDTO.getPublisherId());
            mentionsList.add(mentions);
            //不管是否在线都先存储未读数
            redisUtil.hincr("user:unread:"+atUserId,"atMeMessage",1);
        }
        //插入@表
        this.saveBatch(mentionsList);
        //给被@的用户发送消息
        String message = MessageUtil.getMessage(SystemConstant.SEND_AT_MESSAGE,comments.getPublisherId().toString(), "你被@啦");
        WebSocketServer.sendUsersMessage(message,BeanUtil.copyToList(atUserIds,String.class));
        return Response.success("评论写入成功");
    }


}


